<?php
namespace app\api\model;

use app\model\Base;
use think\facade\Db;
use think\facade\Log;

class Merchant extends Base
{
    public static function induce($id, $amount, $alias = 'score', $type = 'shop_pay', $des = '')
    {
        //钱包增加逻辑 induce deduce locking unlocking
        $info = self::find($id);
        $add = [];
        $add['merchant_id'] = $id;
        $add['amount'] = $amount;
        $add['type'] = $type;
        $add['content'] = Base::$walletLogDesArray[$type] . $des;
        $add['before'] = $info[$alias];
        $add['mode'] = 'inc';

        $update = [];
        $update[$alias] = bcadd($add['before'], $amount);
        $add['after'] = $update[$alias];

        $info->save($update);
        switch ($alias)
        {
            case 'score':{
                MerchantScoreLog::create($add);
            }
                break;
        }
//        if($type == 'admin_recharge'){
//            $add['alias'] = $alias;
//            UserRechargeLog::create($add);
//        }
        return true;
    }

    public static function deduce($id, $amount, $alias = 'score', $type = 'shop_pay', $des = '')
    {
        //钱包增加逻辑 induce deduce locking unlocking
        $info = self::find($id);
        $add = [];
        $add['merchant_id'] = $id;
        $add['amount'] = $amount;
        $add['type'] = $type;
        $add['content'] = Base::$walletLogDesArray[$type] . $des;
        $add['before'] = $info[$alias];
        $add['mode'] = 'dec';

        $update = [];
        $update[$alias] = bcsub($add['before'], $amount);
        if($update[$alias] < 0){
            return false;
        }
        $add['after'] = $update[$alias];

        $info->save($update);
        switch ($alias)
        {
            case 'score':{
                MerchantScoreLog::create($add);
            }
                break;
        }
        return true;
    }

    public static function afterExchange($user_id, $amount, $alias, $type){
        Db::startTrans();
        try {
            //deduce($userId, $amount, $alias = 'money', $level1 = 0, $level2 = 0, $des = '')
            $isDone = self::deduce($user_id, $amount, $alias, $type);
            if($isDone === true)
            {
                //induce($userId, $amount, $alias = 'balance', $type = '', $des = '')
                User::induce($user_id, $amount, $alias, $type);
            }else{
                Db::rollback();
                return false;
            }
            Db::commit();
        } catch (\Exception $exception) {

            Db::rollback();

            Log::error('afterExchange:'.json_encode(['message' => $exception->getMessage(), 'file' => $exception->getFile(), 'line' => $exception->getLine()], JSON_UNESCAPED_UNICODE));
            return false;
        }

        return true;
    }
}